package com.neusoft.resturant.controller;


import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.utils.R;
import com.neusoft.resturant.common.utils.SecurityUtils;
import com.neusoft.resturant.entity.LoginUserVo;
import com.neusoft.resturant.entity.ResShop;
import com.neusoft.resturant.entity.SysUser;
import com.neusoft.resturant.service.IStudentService;
import com.neusoft.resturant.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.http.HttpHeaders;


@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController{

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private RedisTemplate redisTemplate;




    @GetMapping("/get")
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String json = (String) redisTemplate.opsForValue().get(token);
        if (json == null) {
            return R.error("redis没有该用户信息");
        }
        SysUser sysUser = JSON.parseObject(json, SysUser.class);

        sysUser.setPassword(null); // 设置密码字段为null

        return R.success(sysUser);
    }
@GetMapping("/info")
public R getInfo(HttpServletRequest request) {
Long userId=(Long) request.getAttribute("userId");
    System.out.println("当前用户id"+userId);

    return R.success();
}

    @PostMapping("/register")
    public R register(@RequestBody SysUser user) {
      //  System.out.println("Received user: " + user.toString());
        // 检查用户名是否已存在
        SysUser sysUser = sysUserService.selectUserByUserName(user.getUserName());
        if (sysUser != null) {
            return R.error(409, "该用户名已存在");
        }

        // 检查密码是否为空
        if(user.getPassword() == null || user.getPassword().isEmpty()) {
            return R.error(400, "密码不能为空");
        }

        // 生成新的用户并保存
        try {
            sysUser = new SysUser();
            sysUser.setUserName(user.getUserName());
            sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            sysUser.setEmail(user.getEmail());

            sysUser.setPhonenumber(user.getPhonenumber());
            sysUser.setNickName(user.getNickName());
            sysUser.setAvatar(user.getAvatar());
            sysUser.setSex(user.getSex());
            sysUser.setStatus(user.getStatus());
            sysUserService.insertUser(sysUser);
        } catch (Exception e) {
            // 处理可能的数据库操作异常
            return R.error(500, "注册失败: " + e.getMessage());
        }

        // 生成并返回token
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);
        return R.success("注册成功").put("token", token);
    }


    @PostMapping("/login")
    public R login(@RequestBody LoginUserVo userVo) {
        System.out.println(userVo);
        // 1 根据用户名去查询
        SysUser sysUser = sysUserService.selectUserByUserName(userVo.getUserName());
        if (sysUser == null) {
            return R.error(404, "该用户不存在");
        }
        // 2 存在的话，判断密码对不对
        boolean ok = SecurityUtils.matchesPassword(userVo.getPassword(), sysUser.getPassword());
        if (ok) {
            String token = UUID.randomUUID().toString().replace("-", "");
            System.out.println(token);
            redisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);
            return R.success("登录成功").put("token", token);
        } else {
            return R.error("密码错误");
        }
    }
    @PostMapping("/updateUser")
    public R updateInfo(@RequestBody SysUser user) {
        // 从 Redis 中获取用户信息
        String token = request.getHeader("token");
        String  userJson = (String) redisTemplate.opsForValue().get(token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);

        // 更新用户信息，忽略id字段
        sysUser.setUserName(user.getUserName());
        sysUser.setPassword(user.getPassword());
        sysUser.setEmail(user.getEmail());
        sysUser.setPhonenumber(user.getPhonenumber());
        sysUser.setNickName(user.getNickName());
        sysUser.setAvatar(user.getAvatar());
        sysUser.setSex(user.getSex());
        sysUser.setStatus(user.getStatus());

        // 更新数据库中的用户信息
        sysUserService.updateUser(sysUser);

        // 返回成功响应
        return R.success("用户信息更新成功");
    }

}
